<template>
  <div class="admin-list">
    <el-table :data="cpuList" border style="width: 100%" :row-class-name="tableRowClassName">
      <el-table-column prop="username" label="账号名" align="center" width="360"></el-table-column>
      <el-table-column prop="identity" label="权限" align="center" width="360"></el-table-column>
      <el-table-column fixed="right" align="center" label="操作">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope)" type="text" size="small">修改</el-button>
          <el-button type="text" @click="removeClick(scope)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <div class="paginationMain">
        <span @click="firstPage">首页</span>
        <span @click="previous">上一页</span>
        <span @click="mynextPage">下一页</span>
        <span @click="maxPage">尾页</span>
        <i style="line-height:30px;font-size:14px">
          当前页:{{currentPage}}
          总页数:{{allPageNum}}
        </i>
      </div>
    </div>
    <!-- 点击修改按钮弹出的表单框 -->
    <el-dialog title="修改管理员信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="账号名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理权限" :label-width="formLabelWidth">
          <el-select v-model="form.region" placeholder="请选择管理权限">
            <el-option label="超级管理员" value="superAdmin"></el-option>
            <el-option label="普通管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formCancel">取 消</el-button>
        <el-button type="primary" @click="formSure">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      //当前登录的管理员id
      currentAdminID: "",
      //管理员数组
      list: [],
      //当前页
      currentPage: 1,
      //每页显示条数
      perItemNum: 4,
      //管理员总数
      allAdminNum: null,
      //控制修改表单框的显示与否
      dialogFormVisible: false,
      //表单框的值
      form: {
        username: "",
        password: "",
        region: ""
      },
      //控制修改表单框的label宽度
      formLabelWidth: "120px",
      //保存需要修改的管理员id,
      updateID: ""
    };
  },
  computed: {
    //计算list属性
    cpuList() {
      const l = this.list.map(item => {
        if (item.identity == "superAdmin") {
          return {
            username: item.username,
            identity: "超级管理员",
            id: item._id,
            //是否是当前登录的管理员
            isCurrent: this.currentAdminID === item._id
          };
        } else {
          return {
            username: item.username,
            identity: "普通管理员",
            id: item._id,
            //是否是当前登录的管理员
            isCurrent: this.currentAdminID === item._id
          };
        }
      });
      return l;
    },
    //计算总页数
    allPageNum() {
      return Math.ceil(this.allAdminNum / this.perItemNum);
    }
  },
  async mounted() {
    //将当前登录的管理员id存入currentAdminID属性中
    this.currentAdminID = localStorage.id;
    //初始化管理员总数
    this.allAdminNum = await this.getAllAdminCount();
    //初始化管理员列表list数组
    this.list = await this.getAllAdmin();
  },
  methods: {
    //返回表格每一行的类名
    tableRowClassName({ row, rowIndex }) {
      let i = null;
      this.cpuList.forEach((item, index) => {
        if (item.isCurrent) {
          i = index;
        }
      });
      if (rowIndex === i) {
        return "active-row";
      }
      return "";
    },
    //点击取消修改
    formCancel() {
      //关闭修改框
      this.dialogFormVisible = false;
      this.form = {
        username: "",
        password: "",
        region: ""
      };
    },
    //点击修改确认按钮
    async formSure() {
      const { username, password, region } = this.form;
      if (username != "") {
        if (password != "") {
          if (region != "") {
            //先修改数据库数据
            const isSuccess = await this.updateAdmin();
            if (isSuccess) {
              //修改成功
              this.$message({ message: "修改成功", type: "success" });
              //再发接口请求list
              this.list = await this.getAllAdmin();
            } else {
              //修改失败
              this.$message.error("修改失败");
            }
            //关闭修改框
            this.dialogFormVisible = false;
            this.form = {
              username: "",
              password: "",
              region: ""
            };
          } else {
            this.$message("请选择管理权限");
          }
        } else {
          this.$message("请输入修改密码");
        }
      } else {
        this.$message("请输入修改账号");
      }
    },
    //点击修改按钮
    async handleClick(res) {
      //获取当前要修改的管理员id
      const { id } = res.row;
      this.updateID = id;
      //通过当前的修改的用户id，获取用户信息
      const {username,password,identity} = await this.getOneAdmin();
      //将修改框的内容赋初值
      this.form={
        username,password,
        region:identity,
      };
      //点击修改弹出提交框
      this.dialogFormVisible = true;
    },
    //点击删除按钮
    async removeClick(res) {
      if (this.currentAdminID != res.row.id) {
        const isSuccess = await this.delAdmin(res.row.id);
        if (isSuccess) {
          //有一种特殊情况（当前页最后一条被删除，那么删除完后需要跳转到上一页）
          //首先初始化管理员总数
          this.allAdminNum = await this.getAllAdminCount();
          //如果当前页等于了总页数，那就要返回上一页
          if (this.currentPage > this.allPageNum) {
            this.currentPage--;
          }
          //重新渲染管理员表格
          this.list = await this.getAllAdmin();
          this.$message({ message: "删除成功", type: "success" });
        } else {
          this.$message.error("删除失败");
        }
      } else {
        this.$message({
          message: "当前管理员不能进行删除操作",
          type: "warning"
        });
      }
    },

    //点击首页
    async firstPage() {
      this.currentPage = 1;
      this.list = await this.getAllAdmin();
    },
    //点击上一页
    async previous() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.list = await this.getAllAdmin();
      }
    },
    //点击下一页
    async mynextPage() {
      if (this.currentPage < this.allPageNum) {
        this.currentPage++;
        this.list = await this.getAllAdmin();
      }
    },
    //点击尾页
    async maxPage() {
      this.currentPage = this.allPageNum;
      this.list = await this.getAllAdmin();
    },

    //请求获取所有管理员(渲染当前页列表)
    async getAllAdmin() {
      const res = await axios.get("/admin/getAllAdmin", {
        params: { currentPage: this.currentPage, perItemNum: this.perItemNum }
      });
      return res.data;
    },
    //请求获取所有管理员总数
    async getAllAdminCount() {
      const res = await axios.get("/admin/getAllAdminCount");
      return res.data.num;
    },
    //请求修改管理员信息
    async updateAdmin() {
      const res = await axios.post("/admin/updateAdmin", {
        _id: this.updateID,
        username: this.form.username,
        password: this.form.password,
        identity: this.form.region
      });
      return res.data.success;
    },
    //通过id请求该管理员的信息
    async getOneAdmin(){
      const req = await axios.get("/admin/getOneAdmin",{params:{_id:this.updateID}});
      return req.data;
    },
    //请求删除管理员信息
    async delAdmin(id) {
      const res = await axios.post("/admin/delAdmin", {
        _id: id
      });
      return res.data.success;
    }
  }
};
</script>

<style lang="less">
.admin-list {
  .el-main[data-v-452a4712] {
    text-align: center !important;
  }
  .el-table td,
  .el-table th {
    text-align: center !important;
  }
  .pagination .paginationMain {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  .pagination .paginationMain span {
    display: block;
    width: 50px;
    height: 30px;
    border: 1px solid #999;
    line-height: 30px;
    text-align: center;
    margin-right: 10px;
    font-size: 14px;
    border-radius: 5px;
    cursor: pointer;
  }
  .pagination .paginationMain span:hover {
    border: 1px solid #f3a83f;
    color: #f3a83f;
  }
  .el-dialog {
    width: 30% !important;
  }
  .active-row {
    color: rgb(30, 204, 30);
  }
}
</style>